package com.jysz.certificate.service.core;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.jysz.certificate.persistence.dao.core.AttachmentDao;
import com.jysz.certificate.persistence.enums.AttachmentType;
import com.jysz.certificate.persistence.model.core.Attachment;
import com.jysz.certificate.persistence.model.system.User;
import com.jysz.certificate.utils.CommonUtil;
import com.jysz.certificate.utils.DateUtil;
import com.jysz.webcore.ssh.orm.hibernate.ThreadLocalHolder;
import com.jysz.webcore.ssh.service.EntityService;
import com.jysz.webcore.utils.FileUtils;

/**
 * 文件Service
 * @author xuxiaolong
 */
@Service
public class AttachmentService extends EntityService<Attachment, Long, AttachmentDao> {

	private static final Logger LOG =  LoggerFactory.getLogger(AttachmentService.class);
	private static final String QZ_RELEASE="certificate.release.attachment.qz";
	@Resource
	private AttachmentDao dao;
	@Override
	public AttachmentDao getEntityDao() {
		
		return dao;
	}
	
	/**
	 * 定时删除释放单附件
	 */
	public void delJob(){
		LOG.debug("开始执行调度任务：删除附件!当前时间为："+new Date());
		String s=CommonUtil.getProperty(QZ_RELEASE);
		if(CommonUtil.isNotEmpty(s)){
			int days=Integer.parseInt(s);
			if(days>0){
				//DB删除
				Date dateLine=DateUtil.addDays(new Date(), -days);
				dao.delJob(dateLine);
				//磁盘删除
				String dirpath=getRealPath(AttachmentType.RELEASE);
				if(CommonUtil.isEmpty(dirpath))
					return;
				File fd=new File(dirpath);
				if(fd!=null&&fd.isDirectory() ){
					String dstr=DateUtil.formatDate(dateLine, "yyyyMMdd");
					for(File f:fd.listFiles()){
						
						if(f.getName().compareTo(dstr)<0){
							LOG.debug("调度任务，删除目录："+f.getName());
							FileUtils.deleteDir(f);
						}
					}
				}
				
			}
		}
		
	}

	/**
	 * 查询一个对象所关联的所有附件
	 * @param objId 对象ID<Long>
	 * @param type  类型<Enum>
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Attachment> findAll(Long objId,AttachmentType type){
		
		Criteria criteria = dao.createCriteria();
		criteria.add(Restrictions.eq("type", type));
		criteria.add(Restrictions.eq("objId", objId));
		return (List<Attachment>)criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Attachment> findAll(User user,Long objId,AttachmentType type){
		
		Criteria criteria = dao.createCriteria();
		criteria.add(Restrictions.eq("type", type));
		criteria.add(Restrictions.eq("objId", objId));
		if(user!=null)//user不为空时,只查询该用户上传的附件
			criteria.createCriteria("uploadUser").add(Restrictions.eq("id",user.getId()));
		return (List<Attachment>)criteria.list();
	}
	
	/**
	 * 上传附件
	 * @param user 当前登录用户
	 * @param type 附件类型
	 * @param file 文件
	 * @param objId 关联对象ID
	 * @param fileName 文件名
	 */
	public void addFile(User user,AttachmentType type,File file,Long objId,String fileName){
		
		try {
			if(user==null||type==null||file==null||objId==null)
				return;
			String dirpath=getRealPath(type);
			if(dirpath!=null){
				dirpath=dirpath+DateUtil.formatDate(new Date(), "yyyyMMdd");
				String path=FileUtils.add(dirpath, file, fileName);
				Attachment att=new Attachment();
				
				att.setName(CommonUtil.isEmpty(fileName)?file.getName():fileName);
				att.setPath(path);
				att.setType(type);
				att.setObjId(objId);
				att.setUploadDate(new Date());
				att.setUploadUser(user);
				this.save(att);
			}
			
		} catch (IOException e) {
			LOG.error("添加附件出错:"+e.getMessage());
			e.printStackTrace();
		}
	}
	
	public boolean delFile(User currentUser,Long id){
		if(currentUser==null||id==null){
			LOG.debug("删除附件缺少必要参数");
			return false;
		}
		Attachment att= find(id);
		Log.debug("用户:"+currentUser.getName()+" 删除了附件:" +att.getName());
		if(FileUtils.del(att.getPath())){
			destory(att);
			return true;
		}else{
			return false;
		}
	}
	
	/** 删除对象下的所有附件*/
	public void delFile(Long objId,AttachmentType type){
		List<Attachment> list=this.findAll(objId, type);
		for(Attachment att:list){
			FileUtils.del(att.getPath());
			this.destory(att);
		}
		
		String userName = ThreadLocalHolder.get().toString();
		StringBuilder sb=new StringBuilder("用户:");
		sb.append(userName).append(" 删除了类型为：").append(type.getName()).append(",objId为").append(objId).append(" 下的所有附件");
		Log.debug(sb.toString());
	}
	
	public String getRealPath(AttachmentType type){
		String rootPath=CommonUtil.getProperty("attachment.path");
		if(!rootPath.endsWith("/")){
			rootPath=rootPath+"/";
		}
		return rootPath+type.getPath();
	}
}
